#!/usr/bin/python

# See Appendix A of the MXit open protocol specification for an explaination of these steps.

import urllib2
import time
import base64

ts = int(time.time())
r1 = urllib2.urlopen("http://www.mxit.com/res/?type=challenge&getcountries=false&getlanguage=false&getimage=true&ts=%d" % (ts)).read()
print r1

result, url_prefix, session_id, image64 = r1.split(';')[:4]

print result, url_prefix, session_id

image_data = base64.b64decode(image64)
captcha_filename = "captcha.png"
image_file = open(captcha_filename, "wb")
image_file.write(image_data)
image_file.flush()
image_file.close()

print "Please enter the captcha found in %s:" % (captcha_filename)
captcha = raw_input()
print "Enter username:"
login = raw_input()
print "Enter password:"
password = raw_input()

print

reg_url = url_prefix + "?type=getpid&sessionId=%s&ver=5.8.2&login=%s&cat=Y&chalresp=%s&cc=ZA&loc=en_ZA&path=1" % (session_id, login, captcha)
r2 = urllib2.urlopen(reg_url).read()

print r2
print

err, pid = r2.split(';')[:2]

if err == '0':
    print "Paste the following 3 lines in 'account':"
    print login
    print password
    print pid
else:
    print "ERROR"
